package com.dream.mqpushserver.netty;

import com.alibaba.fastjson.JSON;
import com.dream.mqpushserver.common.RequestCommand2;
import com.dream.mqpushserver.common.RpcRequest;
import com.dream.mqpushserver.common.RpcResult;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.lang.reflect.Method;

public class NettyServerHandler2 extends SimpleChannelInboundHandler<RpcRequest> {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("the server has connected "  + ctx.channel().remoteAddress() );
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcRequest request) throws Exception {
        System.out.println("server received tht client request data : "+ JSON.toJSONString(request));

        Object tempClazz = NettyServe.map.get(request.getClassName());
        Method method = tempClazz.getClass().getMethod(request.getMethodName(), request.getParameterTypes());
        Object invoke = method.invoke(tempClazz, request.getArgs());
        System.out.println("this is method invoke : " + JSON.toJSONString(invoke));

        RequestCommand2 requestCommand2 = new RequestCommand2() ;
        RpcResult result = new RpcResult() ;
        result.setData(invoke);
        requestCommand2.setType((byte)2);
        requestCommand2.setLength(JSON.toJSONString(result).getBytes().length);
        requestCommand2.setBytes(JSON.toJSONString(result).getBytes());
        channelHandlerContext.channel().writeAndFlush(requestCommand2);
    }
}
